//
//  AppDelegate.swift
//  weibo
//
//  Created by 孙飞 on 15/12/5.
//  Copyright © 2015年 Sunfei. All rights reserved.
//

import UIKit

let MXSSwitchRootVCNotifation = "MXSSwitchRootVCNotifation"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    var observer: NSObjectProtocol?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        
        // 2.
        window?.rootViewController = MXSUserAccountVM.sharedAccount.userLogon ? defatulRootViewController() : MXSMainTabBarVC()
        
        // 3.成为主窗口并显示
        window?.makeKeyAndVisible()
        
        observer = NSNotificationCenter.defaultCenter().addObserverForName(MXSSwitchRootVCNotifation, object: nil, queue: nil) {[weak self] (noti) -> Void in
            printLog("切换根控制器")
            if noti.object is MXSOAuthVC {
                self?.window?.rootViewController = MXSWelcomeVC()
            }else{
                self?.window?.rootViewController = MXSMainTabBarVC()
            }
        }
        return true
        
    }
    
    
    /// 判断 update
    private func defatulRootViewController() -> UIViewController {
        
        if hasNewVersion() {
            return MXSNewfateVC()
        }else {
            return MXSWelcomeVC()
        }
    }
    
    
    
    //版本
    private func hasNewVersion() -> Bool {
        
        let versionKey = "versionKey"
        
        let localVersion = NSUserDefaults.standardUserDefaults().stringForKey(versionKey)
        
        // 当前版本
        let currentVersion = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"]! as! String
        
        // 当前版本保存
        NSUserDefaults.standardUserDefaults().setObject(currentVersion, forKey: versionKey)
        
        if let local = localVersion where  currentVersion.compare(local)  != NSComparisonResult.OrderedDescending{
            return false
        }
        
        print("\(localVersion),\(currentVersion)")
        
        return true
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(observer!)
    }


}

